//
//  WeatherViewController.m
//  Days
//
//  Created by lanou3g on 16/1/6.
//  Copyright © 2016年 dss. All rights reserved.
//

#import "WeatherViewController.h"
#import "DataHandel.h"





@interface WeatherViewController ()<UITableViewDataSource,UITableViewDelegate,IFlySpeechSynthesizerDelegate>
@property (strong, nonatomic) IBOutlet UITextField *textField;


@property (strong, nonatomic) IBOutlet UIButton *chaBtn;

///时间

@property (strong, nonatomic) IBOutlet UILabel *dateLable;
@property (strong, nonatomic) IBOutlet UILabel *otherTime;

///城市

@property (strong, nonatomic) IBOutlet UILabel *cityLable;

///当前温度

@property (strong, nonatomic) IBOutlet UILabel *currentTemPerature;


///天气晴阴
@property (strong, nonatomic) IBOutlet UILabel *weatherLable;
@property (strong, nonatomic) IBOutlet UILabel *fengli;
@property (strong, nonatomic) IBOutlet UILabel *fengxiang;

///最低温度

@property (strong, nonatomic) IBOutlet UILabel *lowTemperatureLable;

///最高温度
@property(nonatomic,strong)NSString *highestTemperature;
@property (strong, nonatomic) IBOutlet UILabel *highestTemperaturelable;

@property (strong, nonatomic) IBOutlet UIImageView *weatherImageView;
//表示图
@property (strong, nonatomic) IBOutlet UITableView *adviceTableView;
@property (strong, nonatomic) IBOutlet UIWebView *webView;

///建议数组
@property(nonatomic,strong)NSArray *adviceArray;
//建议的结果
@property(nonatomic,strong)NSArray *adviceResultArray;
///建议具体描述数组
@property(nonatomic,strong)NSArray *specificArray;

@end

@implementation WeatherViewController


-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];

  
    self.adviceArray = [NSArray arrayWithObjects:@"穿衣 : ",@"感冒 : ",@"空调 : ",@"污染 : ",@"洗车 : ",@"运动 : ",@"紫外线 : ", nil];
    
    self.webView.backgroundColor =[UIColor clearColor];
    self.webView.opaque = 0;
    
    //自动调整尺寸
    self.webView.scalesPageToFit = YES;
    
    NSString *path = [[NSBundle mainBundle]pathForResource:@"dong" ofType:@"gif"];
    NSData *gifData =[NSData dataWithContentsOfFile:path];
    [self.webView loadData:gifData MIMEType:@"image/gif" textEncodingName:nil baseURL:nil
     ];
    //初始值是北京
    self.textField.text = @"北京";
    [self queryBtnDidclicked:nil];
    
    //定位
    [DataHandel sharedHandel].updateBlock = ^(CLLocationCoordinate2D coor){
      
        [[DataHandel sharedHandel] getAddressWithCoordinate:coor withFinish:^(NSString *address) {
          
            self.textField.text = address;
            

        }];
        
    };
    ///检测TextField里是否有字的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(change ) name:UITextFieldTextDidChangeNotification object:nil];
    
    
    ///城市输入有误的时候的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(errorCity:) name:@"city" object:nil];
    
    
    
    
    // Do any additional setup after loading the view from its nib.
}

#pragma mark -- 输入有误的时候的通知
-(void)errorCity:(NSNotification *)sender{
    
    UIAlertController *  alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"查询城市有误" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       
    }];
    
    [alert addAction:action];
    [self showDetailViewController:alert sender:nil];
    
    
}

#pragma mark -- 检测输入框的改变
-(void)change{
    
    if (self.textField.text.length == 0) {
        [self.chaBtn setUserInteractionEnabled:NO];
        self.chaBtn.alpha = 0.4;
    }else{
        
        [self.chaBtn setUserInteractionEnabled:YES];
        self.chaBtn.alpha = 1;
        
    }
    
}

#pragma mark -- 代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.adviceArray.count == 0) {
        return 7;
    }
    
    return self.adviceArray.count;
}

#pragma mark -- 设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"flag"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:3 reuseIdentifier:@"flag"];
        
    }
    
    cell.backgroundColor = [UIColor clearColor];
    
    NSString *urlStr = [self getURLWithString:self.textField.text];
    
  //  [[DataHandel sharedHandel] getDataWithURL:urlStr withBlock:^(id object) {

      //  [self getAdviceWithObject:object];
        NSString *text = [NSString stringWithFormat:@"%@%@",[self.adviceArray objectAtIndex:indexPath.row],[self.adviceResultArray objectAtIndex:indexPath.row]];
        
        cell.textLabel.text = text;
      
        
    //}];
    
    
    
    
    return cell;
    
    
    
}

#pragma mark -- 选中cell方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    //取消选中的状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    
    if(![[DataHandel sharedHandel]connectedToNetwork ])
    {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"网络连接失败,请查看网络是否连接正常！" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        
    }else{

    
    
    [[DataHandel sharedHandel] getDataWithURL:[self getURLWithString:self.cityLable.text] withBlock:^(id object) {
        [self getAdviceWithObject:object];
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[self.adviceArray objectAtIndex:indexPath.row] message:[self.specificArray objectAtIndex:indexPath.row] preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"好哒" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //点击"好哒"停止读
            [[DataHandel sharedHandel].iFlySpeechSynthesizer stopSpeaking];
        }];
        [alertController addAction:action];
        
        [self showDetailViewController:alertController sender:nil];
        
        ///语音合成并朗读
        //发音人,默认为”xiaoyan”;可以设置的参数列表可参考个 性化发音人列表
        //xiaoyan xiaoyu xiaoqi xiaofeng xiaoxin xiaokun
        [[DataHandel sharedHandel]readWithStr:[self.specificArray objectAtIndex:indexPath.row] byreader:@"xiaoqi" andDelegate:self];

        
        
    }];
    }
    
}


#pragma mark -- 解析字典获取建议的方法
-(void)getAdviceWithObject:(id)object{
    //穿衣建议
    NSString *chuanyi =    [[[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"life"] valueForKey:@"info"] valueForKey:@"chuanyi"] firstObject];
    //具体建议
    NSString *chuanyi1 = [[[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"life"] valueForKey:@"info"] valueForKey:@"chuanyi"] lastObject];
    //感冒
    NSString *ganmao =   [[[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"life"] valueForKey:@"info"] valueForKey:@"ganmao"] firstObject];
    NSString *ganmao1 = [[[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"life"] valueForKey:@"info"] valueForKey:@"ganmao"] lastObject];
    
    //空调-
    NSString *kongtiao =   [[[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"life"] valueForKey:@"info"] valueForKey:@"kongtiao"] firstObject];
    NSString *kongtiao1 =  [[[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"life"] valueForKey:@"info"] valueForKey:@"kongtiao"] lastObject];
    //污染
    NSString *wuran =   [[[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"life"] valueForKey:@"info"] valueForKey:@"wuran"] firstObject];
    NSString *wuran1 = [[[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"life"] valueForKey:@"info"] valueForKey:@"wuran"] lastObject];
    //洗车
    NSString *xiche =    [[[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"life"] valueForKey:@"info"] valueForKey:@"xiche"] firstObject];
    NSString *xiche1 =  [[[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"life"] valueForKey:@"info"] valueForKey:@"xiche"] lastObject];
    //运动
    NSString *yudong =  [[[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"life"] valueForKey:@"info"] valueForKey:@"yundong"] firstObject];
    NSString *yudong1 = [[[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"life"] valueForKey:@"info"] valueForKey:@"yundong"] lastObject];
    
    //紫外线
    NSString *ziwaixian = [[[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"life"] valueForKey:@"info"] valueForKey:@"ziwaixian"] firstObject];
    NSString *ziwaixian1 = [[[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"life"] valueForKey:@"info"] valueForKey:@"ziwaixian"] lastObject];
    
    self.adviceResultArray  = [NSArray arrayWithObjects:chuanyi,ganmao,kongtiao,wuran,xiche,yudong,ziwaixian, nil];
    self.specificArray = [NSArray arrayWithObjects:chuanyi1,ganmao1,kongtiao1,wuran1,xiche1,yudong1,ziwaixian1, nil];
    
    
}


#pragma mark -- 拼接网址
-(NSString *)getURLWithString:(NSString *)string{
    string = [[DataHandel sharedHandel]removeBlankSpaceWithStr:string];
    
    NSString *str = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:string]];
    
    NSString *urlStr = [NSString stringWithFormat:@"http://op.juhe.cn/onebox/weather/query?cityname=%@&key=24924f8af89e5f55560f1ea7925153cb",str ];
    
    
    return urlStr;
}


#pragma mark -- 查询按钮点击
- (IBAction)queryBtnDidclicked:(id)sender {
  


    
    [self.textField endEditing:YES];
    
    if(![[DataHandel sharedHandel]connectedToNetwork ])
    {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"网络连接失败,请查看网络是否连接正常！" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        
    }else{
    
    [self showData];
        
        
    }
    //刷新
    [self.adviceTableView reloadData];
    
    }
    
    
#pragma maek -- 查询按钮点击调用的方法
-(void)showData{
    NSString *urlStr = [self getURLWithString:self.textField.text];
    
    
    
    [[DataHandel sharedHandel]getDataWithURL:urlStr withBlock:^(id object) {
        
          [self getAdviceWithObject:object];
        
        [self.adviceTableView reloadData];
        
        
        //时间
        self.dateLable.text =  [[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"pm25"]valueForKey:@"dateTime"];
        //农历
        self.otherTime.text =   [[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"realtime"]valueForKey:@"moon"];
        //周几
        [[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"realtime"]valueForKey:@"week"];
        //城市
        self.cityLable.text =  [[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"realtime"]valueForKey:@"city_name"];
        
        //pm2.5
        [[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"pm25"]valueForKey:@"pm25"]valueForKey:@"pm25"] ;
        //污染程度
        [[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"pm25"]valueForKey:@"pm25"]valueForKey:@"quality"] ;
        
        
        //湿度
        [[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"realtime"]valueForKey:@"weather"] valueForKey:@"humidity"];
        //天气状况
        self.weatherLable.text =    [[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"realtime"]valueForKey:@"weather"] valueForKey:@"info"];
        
        //当前温度
        self.currentTemPerature.text =  [[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"realtime"]valueForKey:@"weather"] valueForKey:@"temperature"];
        self.currentTemPerature.text = [self.currentTemPerature.text stringByAppendingFormat:@"%@",@"℃"];
        
        //风向
        self.fengxiang.text = [[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"realtime"]valueForKey:@"wind"] valueForKey:@"direct"];
        // 风力
        self.fengli.text =  [[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"realtime"]valueForKey:@"wind"] valueForKey:@"power"];
        
        //七天的温度
        NSArray *array =   [[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"weather"];
        
        ///最高温度
        self.highestTemperaturelable.text = [[[[[[[object valueForKey:@"result"]valueForKey:@"data"]valueForKey:@"weather"] firstObject] valueForKey:@"info"] valueForKey:@"day"] objectAtIndex:2];
        
        self.highestTemperaturelable.text = [self.highestTemperaturelable.text stringByAppendingFormat:@"%@",@"℃"];
        
        ///最低温度
        self.lowTemperatureLable.text =[[[[[[[object valueForKey:@"result"]valueForKey:@"data"]valueForKey:@"weather"] firstObject] valueForKey:@"info"] valueForKey:@"night"] objectAtIndex:2];
        self.lowTemperatureLable.text = [self.lowTemperatureLable.text stringByAppendingFormat:@"%@",@"℃"];
        
        
        //获取当前的时
        float time =  [[[[[object valueForKey:@"result"] valueForKey:@"data"]valueForKey:@"realtime"]valueForKey:@"time"] floatValue] ;
        
        
        NSString *weather = nil;
        //区分白天晚上
        if (time >= 6 && time <= 18) {
            weather =[[[[[[[object valueForKey:@"result"]valueForKey:@"data"]valueForKey:@"weather"] firstObject] valueForKey:@"info"] valueForKey:@"day"] objectAtIndex:0];
        }else{
            weather =[[[[[[[object valueForKey:@"result"]valueForKey:@"data"]valueForKey:@"weather"] firstObject] valueForKey:@"info"] valueForKey:@"night"] objectAtIndex:0];
        }
        
        
        NSString *img = [NSString stringWithFormat:@"w%@.png",weather];
        self.weatherImageView.image = [UIImage imageNamed:img];
        
        for (NSDictionary *dict in array) {
            //日期
            [dict valueForKey:@"date"];
            NSArray *temArray =   [[dict valueForKey:@"info"]valueForKey:@"day"] ;
            //低温
            [temArray objectAtIndex:0];
            //高温
            [temArray objectAtIndex:2];
            //天气情况(晴 阴)
            [temArray objectAtIndex:1];
            
            
        }
        
        
        
        
        
        
        
        
    }];
    
    if(self.textField.text.length != 0){
        //设置代理
        self.adviceTableView.dataSource = self;
        self.adviceTableView.delegate = self;
    }
    

}

#pragma mark -- 语音合成代理方法
//合成结束，此代理必须要实现
- (void) onCompleted:(IFlySpeechError *) error{
    
}
//合成开始
- (void) onSpeakBegin{
    
}
//合成缓冲进度
- (void) onBufferProgress:(int) progress message:(NSString *)msg{
}
//合成播放进度
- (void) onSpeakProgress:(int) progress{
}

@end
